import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Random;
import java.util.Scanner;

import javax.swing.*;

public class TypingSpeed extends JFrame implements KeyListener, Runnable , Game  {
	String[] line = new String[8];
	String[] typed = new String[8];
	int lineNumber = 0;
	int numOfLines = 4;
	boolean shifted = false;
	Thread mainThread;
	long time;
	
	public static void main(String args[]) {
		TypingSpeed p = new TypingSpeed();
		p.setSize(1024, 820);
		p.setVisible(true);
		p.setResizable(false);
		p.addKeyListener(p);
		
	}

	// This is the default constructor
	public TypingSpeed() {
		getInput();
		time = System.nanoTime();
		mainThread = new Thread(this);
		mainThread.start();
	} // end default constructor
	
	// This gets the sentences from an input file
	public void getInput() {
		try {
			Scanner reader = new Scanner(new FileReader(new File("in.txt")));
			for(int i = 0; i < numOfLines; i++)
				line[i] = reader.nextLine();
			for(int i = 0; i < numOfLines; i++)
				typed[i] = "";
			reader.close();
		}catch(FileNotFoundException e) {System.exit(0);}
	} // end getInput method
	
	// This method is used to determine if shift is pressed (to signify to 
	// draw the String in upper case
	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_SHIFT)
			shifted = true;
		repaint();
		
	} // end keyPressed

	//
	public void keyReleased(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_SHIFT)
			shifted = false;
		repaint();
	} // end keyReleased method

	// This 
	public void keyTyped(KeyEvent e) {
			
		if(typed[lineNumber].length() != 0 && (e.getKeyChar() + "").equals("\u0008"))  
			typed[lineNumber] = typed[lineNumber].substring(0, typed[lineNumber].length()-1);
		else
			typed[lineNumber] += shifted? (e.getKeyChar()+"").toUpperCase(): e.getKeyChar();
		repaint();
	
	} // end keyTyped method

	//
	public void run() {
		while(true) {
			if(typed[lineNumber].equals(line[lineNumber]) && line[lineNumber] != "")  
				lineNumber++;
			if(lineNumber > numOfLines - 1) {
				System.out.println((double)(System.nanoTime() - time) / 1000000000d / 60d);
				System.exit(0); 
			}
		} // end while
	} // end run method

	public void getInfo() {
		// TODO Auto-generated method stub
		
	}
	
	// This method paints the screen with the appropriate strings
	public void paint(Graphics g) {
		g.clearRect(0, 0, this.getWidth(), getHeight());
		g.setFont(new Font("Times", Font.PLAIN, 32));
		for(int i = 0; i < numOfLines; i++) {
			g.drawString(line[i], 100, 90 + 80*i);
			g.drawString(typed[i], 100, 127 + 80*i);
		} // end for
	} // end paint method
}
